#coding=utf-8

from django.shortcuts import render, render_to_response
from django.http import HttpResponse
from django.views.decorators.gzip import gzip_page
from django.views.decorators.cache import cache_page
from django.core.cache import cache
from django.contrib.sessions.models import Session
from myapp.models import Article
from django.http import Http404, HttpResponseServerError, HttpResponseRedirect
from functools import wraps
from django.utils.decorators import decorator_from_middleware, available_attrs
from django.views.decorators.http import require_http_methods
from django.views.generic import View
from django.views.decorators.csrf import csrf_exempt


def auth_test():
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            print('inner start')
            print(request)
            print(dir(request))

            # 注意点 Class View => req = request.request
            req = request.request
            # def view => req = request
            # req = request
            if req.COOKIES.get('sessionid') is None:
                return HttpResponseRedirect('/user_login/')
            return func(request, *args, **kwargs)
        return inner
    return decorator


def check_session(request):
    SESSION = request.session
    if not ('user_id' in SESSION and SESSION['user_id']):
        return HttpResponseRedirect('/user_login2/')


@auth_test()
def auth_view(request, *args, **kwargs):
    print('='*20)
    print(request)
    _check_session = check_session(request)
    if isinstance(_check_session, HttpResponseRedirect):
        return _check_session
    return HttpResponse("auth" * 2)


class MyView(View):
    @auth_test()
    def get(self, request, *args, **kwargs):
        print('='*20)
        print(request)
        return HttpResponse('my view get result')


@gzip_page
def viewFunc(request):
    ariticle = Article.objects.all()
    return HttpResponse("hello" * 2)



def view404(request):
    if request.GET.get('y'):
        return HttpResponse('aa')
    else:
        raise Http404('Only POSTs are allowed')



def view500(request):
    try:
        1 / 0
        return HttpResponse('ok')
    except:
        raise HttpResponseServerError('500 POSTs are allowed')



# @cache_page(10)
def home(request):
    # 一次获取单个缓存键值
    cache.set('my_key', 'hello, world!2', 5)
    cache.set('news', 'cache news list2', 5)

    # 一次获取多个缓存键值
    a = cache.get_many(['my_key', 'news', 'article'])
    print(a)
    # print(b)
    # print(c)
    print(a.get('my_key'))

    if cache.has_key('article'):
        articel = cache.get('article')
        print('cache articel')
        print(articel)
    else:
        # Article
        articel = Article.objects.all()
        print('queryset articel')
        print(articel)
        cache.set('article', articel)

    # request.session['test'] = 'test value'
    # s = Session.objects.all()
    # for i in s:
    #     print(i.get_decoded())
    # data1 = [
    #     {'headline': u'Django is cool', 'content': u'Yeah.', u'reporter_id': 1, u'id': 1},
    #     {'headline': u'Django is very cool', 'content': u'very Yeah.', u'reporter_id': 2, u'id': 2},
    #     {'headline': u'zhuwenzhuo', 'content': u'', u'reporter_id': 1, u'id': 3},
    #     {'headline': u'zhuwenzhuo2', 'content': u'', u'reporter_id': 1, u'id': 4},
    #     {'headline': u'zhuwenzhuo3', 'content': u'', u'reporter_id': 1, u'id': 5},
    #     {'headline': u'zhuwenzhuo3', 'content': u'test test', u'reporter_id': 1, u'id': 6},
    #     {'headline': u'zhuwenzhuo3', 'content': u'test test33', u'reporter_id': 2, u'id': 7},
    #     {'headline': u'zhuwenzhuo4', 'content': u'4444', u'reporter_id': 1, u'id': 8}
    # ]
    return render_to_response("index.html", {'name': cache.get('my_key'), 'news': cache.get('news'), 'articel': articel})


def login(requtest):
    SESSION = requtest.session
    SESSION['user_id'] = '1'
    SESSION['user_name'] = 'zhuxh'
    return HttpResponse('%s is login ok!' % SESSION.get('user_name'))